package net.csdn.business.notify.common.pipeline;

import lombok.Data;
import net.csdn.business.notify.common.enums.ProcessStatusEnum;
import net.csdn.business.notify.common.model.vo.NotifyResponseVO;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * @ClassName ProcessController
 * @Description 流程控制器
 * @Author zhangyl
 * @Date 2023/11/28 18:10
 */
@Data
public class ProcessController {

    /**
     * 模板映射
     */
    private Map<String, ProcessTemplate> templateConfig = null;


    /**
     * 执行责任链
     *
     * @param context
     * @return 返回上下文内容
     */
    public ProcessContext process(ProcessContext context) {

        /**
         * 前置检查
         */
        // 上下文
        if (Objects.isNull(context)) {
            context = new ProcessContext();
            context.setResponse(NotifyResponseVO.fail(ProcessStatusEnum.CONTEXT_IS_NULL));
            return context;
        }
        // 业务代码
        String processType = context.getProcessType();
        if (StringUtils.isBlank(processType)) {
            context.setResponse(NotifyResponseVO.fail(ProcessStatusEnum.PROCESS_TYPE_IS_NULL));
            return context;
        }
        // 执行模板
        ProcessTemplate processTemplate = templateConfig.get(processType);
        if (Objects.isNull(processTemplate)) {
            context.setResponse(NotifyResponseVO.fail(ProcessStatusEnum.PROCESS_IS_NULL));
            return context;
        }

        // 执行模板列表
        List<BusinessProcess> processList = processTemplate.getProcessList();
        if (Objects.isNull(processList) || processList.size() == 0) {
            context.setResponse(NotifyResponseVO.fail(ProcessStatusEnum.PROCESS_ACTION_IS_NULL));
            return context;
        }

        /**
         * 遍历流程节点
         */
        for (BusinessProcess businessProcess : processList) {
            businessProcess.process(context);
            if (context.getNeedBreak()) {
                break;
            }
        }
        return context;
    }

}
